﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Components.PrefabPool
{
    public class PrefabPools : MonoSingleton<PrefabPools>
    {
        private readonly Dictionary<int, PrefabPool> _pools = new Dictionary<int, PrefabPool>();
        public PrefabPool CreateOrGetPool(GameObject prefab, PrefabPoolSetting setting)
        {
            var id = prefab.GetInstanceID();
            if (!_pools.TryGetValue(id, out var pool))
            {
                pool = new PrefabPool(prefab, transform, ref setting);
                _pools.Add(id, pool);
            }

            return pool;
        }

        public void ReleasePool(GameObject prefab)
        {
            var id = prefab.GetInstanceID();
            if (!_pools.TryGetValue(id, out var pool)) return;
            
            pool.Clean();
            _pools.Remove(id);
        }

        public void ReleaseAll()
        {
            foreach (var item in _pools)
            {
                var pool = item.Value;
                pool.Clean();
            }
            _pools.Clear();
        }

        private void Update()
        {
            foreach (var item in _pools)
            {
                var pool = item.Value;
                pool.Tick();
            }
        }
    }
}